package ro.romanescu.utilities;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Generic utility class.
 */
public final class Utilities {
  public static final Log log = LogFactory.getLog( Utilities.class );

  /**
   * Transform safely an object into boolean representation.
   * @param o Object to be transformed. For boolean value true, o.toString() 
   * must return "true" string.
   * @param defaultValue Default value when transformation fails.
   * @return boolean representation
   */
  public static boolean toBool( Object o, boolean defaultValue ) {
    boolean ret = defaultValue;
    if( o != null ) {
      ret = Boolean.parseBoolean( o.toString() );
    }
    return ret;
  }


  /**
   * Transform safely an object into boolean representation.
   * @param o Object to be transformed. For boolean value true, o.toString() 
   * must return "true" string.
   * @return boolean representation, false if transformation fails.
   */
  public static boolean toBool( Object o ) {
    return toBool( o, false );
  }


  /**
   * Transform an object into its string representation, handling null values.
   * @param val object
   * @return string representation. "" if val was null or empty string
   */
  public static String toString( Object val ) {
    String ret = "";
    if( val != null ) {
      ret = val.toString();
    }
    return ret;
  }


  /**
   * Transform an object into integer.
   * @param val Value
   * @return 0 if error, otherwise integer
   */
  public static int toInt( Object val ) {
    int ret = 0;
    if( val != null ) {
      ret = Integer.parseInt( val.toString() );
    }
    return ret;
  }


  /**
   * Transform safely an object into double representation.
   * @param val Value to be transformed
   * @return double value or 0 if error occurrs
   */
  public static double toDouble( Object val ) {
    double ret = 0.0;
    if( val != null ) {
      try {
        ret = Double.parseDouble( val.toString() );
      } catch( NumberFormatException ex ) {
        log.error( String.format( "Unable to transform %s to double value", val ), ex );
      }
    }
    return ret;
  }
}
